package com.mdt.rtm;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class WebAuthentication {

	public static boolean authenticate(String repositoryUrl, String username, String password,
			String authUrl) {

		// Create an instance of HttpClient.
		HttpClient client = new HttpClient();
		
		// Create a method instance.
		PostMethod method = new PostMethod(repositoryUrl);


		// Provide custom retry handler is necessary
		method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
				new DefaultHttpMethodRetryHandler(3, false));

		int questionMark = authUrl.indexOf("?");
		String apiToConvert = authUrl.substring(questionMark + 1);

		String api = "";
		try {
			api = URLEncoder.encode(apiToConvert,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}

		NameValuePair[] data = {
				new NameValuePair("action",
						repositoryUrl),
				new NameValuePair("username", username),
				new NameValuePair("password", password),
				new NameValuePair("remember", ""),
				new NameValuePair("loginsubmit", "Login"),
				new NameValuePair("continue", "home"),
				new NameValuePair("api", api), new NameValuePair("u", "1") };
		method.setRequestBody(data);

		try {
			// Execute the method.

			int statusCode = client.executeMethod(method);

			if (statusCode != HttpStatus.SC_MOVED_TEMPORARILY) {
				System.err.println("Method failed: " + method.getStatusLine());
			}

			for (Header header : method.getResponseHeaders()) {
				//System.out.println(header.getName() + " " + header.getValue());
				if (header.getName().equalsIgnoreCase("Location")) {

					if (header.getValue().indexOf("login/?tryAgain") > 0) {
						return false;
					} else {
						// Create a method instance.
						GetMethod method2 = new GetMethod(header.getValue());
						
						// Provide custom retry handler is necessary
						method2.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
								new DefaultHttpMethodRetryHandler(3, false));
	
						try {
						  // Execute the method.
						  int statusCode2 = client.executeMethod(method2);
	
						  if (statusCode2 != HttpStatus.SC_OK) {
						    System.err.println("Method failed: " + method2.getStatusLine());
						  }
	
						  // Read the response body.
						  byte[] responseBody2 = method2.getResponseBody();
						  
						  PostMethod method3 = new PostMethod(header.getValue());
						  
						  NameValuePair[] data3 = {new NameValuePair("authorize_yes", "OK, I'll allow it")};
						  method3.setRequestBody(data3);
						  
						  int statusCode3 = client.executeMethod(method3);
						  
						  if(statusCode3 != HttpStatus.SC_OK) {
							    System.err.println("Method failed: " + method3.getStatusLine());
						  }
						  
	
						  // Deal with the response.
						  // Use caution: ensure correct character encoding and is not binary data
						  //System.out.println(new String(responseBody2));
						  return true;
	
						} catch (HttpException e) {
						  System.err.println("Fatal protocol violation: " + e.getMessage());
						  e.printStackTrace();
						} catch (IOException e) {
						  System.err.println("Fatal transport error: " + e.getMessage());
						  e.printStackTrace();
						} finally {
						  // Release the connection.
						  method2.releaseConnection();
						}
					}

				}
			}

			// Read the response body.
			//byte[] responseBody = method.getResponseBody();

			// Deal with the response.
			// Use caution: ensure correct character encoding and is not binary data
			//System.out.println(new String(responseBody));

		} catch (HttpException e) {
			System.err.println("Fatal protocol violation: " + e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			System.err.println("Fatal transport error: " + e.getMessage());
			e.printStackTrace();
		} finally {
			// Release the connection.
			method.releaseConnection();
		}
		return false;
	}

}
